import { HubConnectionBuilder, type HubConnection } from '@microsoft/signalr';
import pinia from '@/stores';
import useUserStore from '@/stores/modules/user';
const userStore = useUserStore(pinia);
const DEFFAULT_URL = `${import.meta.env.VITE_APP_BASE_API}/hub?access_token=${userStore.tokenData?.accessToken}`;

// 配置
export interface WRequestConfig {
  url: string;
}

export enum HttpTransportType {
  none = 0,
  webSockets = 1,
  serverSentEvents = 2,
  longPolling = 4
}
//  /// <summary>Specifies that no transport is used.</summary>
//  None = 0,
//  /// <summary>Specifies that the web sockets transport is used.</summary>
//  WebSockets = 1,
//  /// <summary>
//  /// Specifies that the server sent events transport is used.
//  /// </summary>
//  ServerSentEvents = 2,
//  /// <summary>Specifies that the long polling transport is used.</summary>
//  LongPolling = 4,
// {
//     "type": 1,
//     "target": "MessageNotification",
//     "arguments": [
//         {
//             "id": "3a11d943-dbc6-4150-bbd7-aa639bf3fd1d",
//             "title": "676776",
//             "content": "<p>6767</p>",
//             "sendTime": "2024-04-10T16:19:18.107782+08:00",
//             "sendUserId": "3a114eb4-8d58-ab1d-4971-f5ab5f615d45",
//             "sendUserName": "admin"
//         }
//     ]
// }
// 返回数据
export interface WReposnseData<T> {
  type: HttpTransportType;
  target: string;
  arguments: T;
}

export class Ws {
  private connection: HubConnection;
  // 基础配置，url和超时时间
  private baseConfig: WRequestConfig = { url: DEFFAULT_URL };
  constructor(config?: WRequestConfig) {
    const configInfo = Object.assign(this.baseConfig, config);
    // 创建WebSocket连接
    this.connection = new HubConnectionBuilder()
      .withUrl(configInfo.url) // 连接地址
      .withAutomaticReconnect() // 自动重链
      .build();
  }

  // 开始链接
  public start() {
    this.connection
      .start()
      .then(() => {
        console.log('WebSocket连接已建立');
      })
      .catch((err) => {
        console.error('WebSocket连接失败:', err);
      });
  }

  // 关闭
  public stop() {
    this.connection
      .stop()
      .then(() => {
        console.log('WebSocket连接已关闭');
      })
      .catch((err) => {
        console.error('WebSocket连接关闭失败:', err);
      });
  }

  // 获取链接
  public getConnection(): HubConnection {
    return this.connection;
  }

  // 发送数据
  public send<T>(methodName: string, message: T) {
    this.connection.invoke(methodName, message).catch(function (err) {
      return console.error(err.toString());
    });
  }
}
